<?php
/**
 * 零起飞-(07FLY-CRM)
 * ==============================================
 * 版权所有 2015-2028   成都零起飞网络，并保留所有权利。
 * 网站地址: http://www.07fly.xyz
 * ----------------------------------------------
 * 如果商业用途务必到官方购买正版授权, 以免引起不必要的法律纠纷.
 * ==============================================
 * Author: kfrs <goodkfrs@QQ.com> 574249366
 * Date: 2019-10-3
 */

namespace app\ten\logic;

/**
 * 租户逻辑
 */
class TenUser extends TenBase
{

    /**
     * 列表
     */
    public function getTenUserList($where = [], $field = true, $order = 'create_time desc', $paginate = DB_LIST_ROWS)
    {
        $list = $this->modelTenUser->getList($where, $field, $order, $paginate);
        foreach ($list as &$row) {
            $row['tenant_nums'] = $this->modelTenTenantUser->stat(['ten_user_id' => $row['id']], 'count');
            // 获取创建的企业名
            $row['create_company_name'] = arr2str($this->modelTenTenant->getColumn(['init_admin_id' => $row['id']], 'company'));
            // 获取默认登录加载企业
            $row['init_company_name'] =$this->modelTenTenant->getValue(['id' => $row['init_tenant_id']], 'company');

            // 获取所属企业名，一般是帐企业管理创建
            $row['owner_company_name'] =$this->modelTenTenant->getValue(['id' => $row['ten_tenant_id']], 'company');

        }
        return $list;
    }

    /**
     * 添加
     */
    public function tenUserAdd($data = [])
    {
        $validate_result = $this->validateTenUser->scene('add')->check($data);
        if (!$validate_result) {
            return [RESULT_ERROR, $this->validateTenUser->getError()];
        }
        $url = url('show');
        $data['password'] = data_md5_key($data['password']);//密码加密
        $result = $this->modelTenUser->setInfo($data);
        $result && action_log('新增', '新增租户：name' . $data['username']);
        return $result ? [RESULT_SUCCESS, '添加成功', $url] : [RESULT_ERROR, $this->modelTenUser->getError()];
    }

    /**
     * 编辑
     */
    public function tenUserEdit($data = [])
    {
        $validate_result = $this->validateTenUser->scene('edit')->check($data);
        if (!$validate_result) {
            return [RESULT_ERROR, $this->validateTenUser->getError()];
        }
        $url = url('tenUser');
        $result = $this->modelTenUser->setInfo($data);
        $result && action_log('编辑', '编辑租户，name：' . $data['username']);
        return $result ? [RESULT_SUCCESS, '编辑成功', $url] : [RESULT_ERROR, $this->modelTenUser->getError()];
    }

    /**
     * 删除
     */
    public function tenUserDel($where = [])
    {
        $result = $this->modelTenUser->deleteInfo($where, true);
        $result && action_log('删除', '删除租户，where：' . http_build_query($where));
        return $result ? [RESULT_SUCCESS, '删除成功'] : [RESULT_ERROR, $this->modelTenUser->getError()];
    }

    /**
     * 获取信息
     */
    public function getTenUserInfo($where = [], $field = true)
    {
        $info = $this->modelTenUser->getInfo($where, $field);
        if (!empty($info)) {
            $this->modelTenTenantUser->alias('a');
            $this->modelTenTenantUser->join = [
                [SYS_DB_PREFIX . 'ten_tenant b', 'a.ten_tenant_id = b.id']
            ];
            $field = 'b.id,b.company,b.start_date,b.stop_date,b.init_admin_id,b.remark';
            $info['tenant_list'] = $this->modelTenTenantUser->getList(['a.ten_user_id' => $info['id']], $field);
        }
        return $info;
    }

    /**
     * 创建租户
     */
    public function userCreateTenant($data)
    {
        if (empty($data['company']) || empty($data['ten_tenant_type_id']) || empty($data['ten_user_id'])) {
            throw_response_error('参数错误');
        }
        $data['init_admin_id'] = $data['ten_user_id'];//租户管理员
        $data['start_date'] = empty($data['start_date']) ? date('Y-m-d') : $data['start_date'];
        $data['stop_date'] = empty($data['stop_date']) ? date('Y-m-d') : $data['stop_date'];
        $tenantId = $this->modelTenTenant->setInfo($data);
        // 创建租户管理员与用户关系
        if (!empty($tenantId)) {
            $tenantUser = [
                'ten_tenant_id' => $tenantId,
                'ten_user_id' => $data['ten_user_id'],
            ];
            $this->modelTenTenantUser->setInfo($tenantUser);
        }
        $tenantId && action_log('新增', '用户创建租户，name：' . $data['company']);
        return $tenantId ? [RESULT_SUCCESS, '添加成功'] : [RESULT_ERROR, $this->modelTenUser->getError()];
    }

    /**
     * 重置密码
     */
    public function userResetPwd($data = [])
    {
        $validate_result = $this->validateTenUser->scene('resetpassword')->check($data);
        if (!$validate_result) {
            return [RESULT_ERROR, $this->validateTenUser->getError()];
        }
        if ($data['password'] != $data['password_confirm']) {
            throw_response_error('两次密码不一致');
        }
        $md5password = data_md5_key($data['password']);
        $where['id'] = ['in', $data['id']];
        $result = $this->modelTenUser->setFieldValue($where, 'password', $md5password);
        $result && action_log('编辑', '重置密码修改，name：' . $data['username']);
        $url = url('index/index');
        return $result ? [RESULT_SUCCESS, '修改成功', $url] : [RESULT_ERROR, $this->modelTenUser->getError()];
    }
}